package com.example.ntier.model.dal;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.example.ntier.model.entity.GenericEntity;

public abstract class AbstractDAL<K, E extends GenericEntity<K>> implements GenericDAL<K, E> {

	private static final String DB_URL = "jdbc:oracle:thin:@10.3.21.25:1521:xe";
	private static final String DB_USER_NAME = "ex";
	private static final String DB_PASSWORD = "ex";

	// private final Map<String, Object> dependecies;
	private final String tableName;

	public AbstractDAL(String tableName) {
		this.tableName = tableName;
		// this.dependecies = new HashMap<String, Object>();
	}

	@Override
	public int getCount() throws SQLException {
		int count = 0;
		try (Connection connection = createConnection()) {
			try (Statement statement = connection.createStatement()) {
				final String sqlCmd = "SELECT COUNT(*) FROM " + tableName;
				try (ResultSet resultSet = statement.executeQuery(sqlCmd);) {
					if (resultSet.next()) {
						count = resultSet.getInt(1);
					}
				}
			}
		}
		return count;
	}

	Connection createConnection() throws SQLException {
		return DriverManager.getConnection(DB_URL, DB_USER_NAME, DB_PASSWORD);
	}

	// void addDAL(String key, Object dal) {
	// this.dependecies.put(key, dal);
	// }
	//
	// Object getDAL(String key) {
	// return dependecies.get(key);
	// }

	abstract E createEntity(ResultSet resultSet) throws SQLException;
}
